package main

import (
	"flag"
	"fmt"
	"golang.org/x/sync/errgroup"
	"lancer/client"
	"lancer/common"
	"lancer/conf"
	"lancer/worker"
	"log"
	"time"
)

var (
	confFile string
)

func initArgs() {
	flag.StringVar(&confFile, "config", "./conf/config.json", "指定config.json文件")
	flag.Parse()
}

func main() {
	var (
		err    error
		output string
	)

	log.Println("collection web dev restart...")

	//初始化命令行
	initArgs()

	//读取配置文件
	if err = conf.InitConfig(confFile); err != nil {
		log.Println("加载配置文件错误:", err)
		panic(err)
	}

	//初始化执行器
	if err = worker.InitExecutor(); err != nil {
		log.Println("执行器错误:", err)
		panic(err)
	}

	inputStr := "collection web dev restart"
	//等待用户确认再往下执行
	common.Ask(inputStr)

	//连接ssh
	if err = client.InitSsh(); err != nil {
		log.Println("ssh服务器错误:", err)
		panic(err)
	}

	//查找文件是否存在
	log.Println("查找文件是否存在")
	if output, err = client.GSshClientHandle.Run("find /home/collect  -name singo-collection-linux64"); err != nil {
		log.Println("ssh服务器查找文件错误:", err)
		panic(err)
	}
	log.Println("查找的文件名：", output)

	//判断文件是否存在 存在则mv 不存在则直接上传
	allFileName := "/home/collect/singo-collection-linux64"
	if output != (allFileName + "\n") {
		log.Println("文件不存在")
	}

	//chmod 755 包 权限
	log.Println("给包赋值755权限")
	if output, err = client.GSshClientHandle.Run("chmod 755 /home/collect/singo-collection-linux64"); err != nil {
		log.Println("ssh服务器chmod 755错误:", err)
		panic(err)
	}

	//ps -ef | grep 查看进程
	log.Println("执行进程id查找...")
	if output, err = client.GSshClientHandle.Run("ps -elf | grep singo-collection-linux64 | grep -v grep | head -n 1|awk '{print $4}'"); err != nil {
		log.Println("ssh服务器ps -ef错误:", err)
		panic(err)
	}

	if output != "" {
		//kill -9 进程
		log.Println("执行：kill - 9 " + output)
		if output, err = client.GSshClientHandle.Run("kill -9 " + output); err != nil {
			log.Println("ssh服务器kill -9错误:", err)
			panic(err)
		}
		log.Println(output)
	}

	//启动进程
	log.Println("启动进程脚本")
	date := time.Now().Format("2006-01-02")

	eg := new(errgroup.Group)
	eg.Go(func() (err error) {
		//runCommand := fmt.Sprintf(`cd /home/collect && /bin/bash ./start-run.sh > auto-%s.log 2>&1`, date)
		//log.Println("执行命令", runCommand)
		//result, err := client.GSshClientHandle.RunAsync(runCommand, 5)
		//log.Println("返回结果:", result)

		runCommand := fmt.Sprintf(`cd /home/collect && /usr/bin/nohup ./singo-collection-linux64 > auto-%s.log 2>&1 &`, date)
		log.Println("执行命令", runCommand)
		result, err := client.GSshClientHandle.Run(runCommand)
		log.Println("返回结果:", result)
		return err
	})

	if err := eg.Wait(); err != nil {
		log.Println("执行启动报错:", err)
	}

	log.Println("collection web dev restart finish")
}
